package win.smartown.android.library.richtexteditor;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v7.widget.LinearLayoutCompat;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by Smartown on 2017/11/8.
 */
public class RichTextEditor extends ScrollView {

    private RichTextEditorContent richTextEditorContent;

    public RichTextEditor(Context context) {
        super(context);
        init();
    }

    public RichTextEditor(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public RichTextEditor(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        richTextEditorContent = new RichTextEditorContent(getContext());
        addView(richTextEditorContent);
    }

    public String getContent() {
        return richTextEditorContent.getContent();
    }

    private static class RichTextEditorContent extends LinearLayoutCompat implements OnClickListener {

        private List<Content> contentList;
        private HashMap<String, ImageView> imageViewHashMap;
        private int padding;

        public RichTextEditorContent(Context context) {
            super(context);
            init();
        }

        private void init() {
            contentList = new LinkedList<>();
            imageViewHashMap = new HashMap<>();
            setOrientation(VERTICAL);
            setGravity(Gravity.CENTER_HORIZONTAL);
            padding = getResources().getDimensionPixelSize(R.dimen.dp16);
            setPadding(padding, 0, padding, 0);
            addLastAddItem();
        }

        private String getContent() {
            List<Content> results = new LinkedList<>();
            for (int i = 0; i < contentList.size(); i++) {
                final Content content = contentList.get(i);
                final int type = content.getType();
                switch (type) {
                    case 1:
                        final EditText editText = getChildAt(i).findViewById(R.id.edit);
                        if (editText.length() > 0) {
                            results.add(new Content(1, editText.getText().toString()));
                        }
                        break;
                    default:
                        if (!TextUtils.isEmpty(content.getValue())) {
                            results.add(content);
                        }
                        break;
                }
            }
            return new Gson().toJson(results);
        }

        private void addItem(int position, Content content) {
            contentList.add(position, content);
            switch (content.getType()) {
                case 1:
                    addEditItem(position, content);
                    break;
                case 2:
                case 3:
                    addImageItem(position, content);
                    break;
            }
        }

        private void addEditItem(int position, Content content) {
            View view = LayoutInflater.from(getContext()).inflate(R.layout.editor_edit, null);
            View addView = view.findViewById(R.id.add);
            addView.setTag(content);
            addView.setOnClickListener(this);
            addView(view, position);
        }

        private void addImageItem(int position, Content content) {
            View view = LayoutInflater.from(getContext()).inflate(R.layout.editor_image, null);
            View addView = view.findViewById(R.id.add);
            addView.setTag(content);
            addView.setOnClickListener(this);
            ImageView imageView = view.findViewById(R.id.image);
            imageViewHashMap.put(content.getValue(), imageView);
            Glide.with(getContext()).load(content.getValue()).asBitmap().listener(new RequestListener<String, Bitmap>() {
                @Override
                public boolean onException(Exception e, String model, Target<Bitmap> target, boolean isFirstResource) {
                    return false;
                }

                @Override
                public boolean onResourceReady(Bitmap resource, String model, Target<Bitmap> target, boolean isFromMemoryCache, boolean isFirstResource) {
                    ImageView imageView = imageViewHashMap.get(model);
                    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
                    layoutParams.height = (int) (((float) RichTextEditorContent.this.getWidth() - 4 * padding) / resource.getWidth() * resource.getHeight() + 2 * padding);
                    imageView.setLayoutParams(layoutParams);
                    imageViewHashMap.remove(model);
                    return false;
                }
            }).into(imageView);
            addView(view, position);
        }

        private void addLastAddItem() {
            View view = LayoutInflater.from(getContext()).inflate(R.layout.editor_add_last, this, true);
            view.setId(R.id.add_last);
            view.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            int id = view.getId();
            Content content;
            if (id == R.id.add) {
                Content positionContent = (Content) view.getTag();
                if (positionContent.getType() == 1) {
                    content = new Content(2, "http://c.hiphotos.baidu.com/image/h%3D300/sign=e8a7dd4cd3f9d72a0864161de42b282a/4ec2d5628535e5dd15fa1cac7cc6a7efcf1b62eb.jpg");
                } else {
                    content = new Content(1, "");
                }
                addItem(contentList.indexOf(positionContent), content);
            } else if (id == R.id.add_last) {
                addItem(contentList.size(), new Content(1, ""));
            }
        }

    }

}
